package br.com.skolar.server;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;

import br.com.skolar.client.Answer;
import br.com.skolar.client.Question;

import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.google.inject.persist.finder.Finder;

public class QuestionRepositoryImpl implements QuestionRepository {
	@Inject EntityManager em;
	@Inject QuestionFinder finder;
	
	@Override
	public List<Question> searchQuestions() {
		return finder.searchQuestions();
	}

	public interface QuestionFinder {
		@Finder(query="select q from Question q", returnAs=ArrayList.class)
		List<Question> searchQuestions();
		
		@Finder(query="select a from Answer a where a.questionId = :id", returnAs=ArrayList.class)
		List<Answer> loadAnswers(@Named("id") Long questionId);
	}

	@Override
	public Question save(Question question) {
		return em.merge(question);
	}

	@Override
	public Answer save(Answer answer) {
		return em.merge(answer);
	}

	@Override
	public List<Answer> loadAnswers(Question question) {
		return finder.loadAnswers(question.getId());
	}
}